package day14;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import day13.JDBCUtil;

public class Demo {
	// 事物
		@Test
		public void test1() {
			Connection connection = null;
			PreparedStatement statement = null;
			try {
				connection = JDBCUtil.getConnection();
				String sql1 = "UPDATE account SET money=money-1000 WHERE name='张三'";
				statement = connection.prepareStatement(sql1);
				int count1 = statement.executeUpdate();
				System.out.println("count1: " + count1);
				
				int i = 3 / 0; // ArithmeticException
				
				String sql2 = "UPDATE account SET money=money+1000 WHERE name='李四'";
				statement = connection.prepareStatement(sql2);
				int count2 = statement.executeUpdate();
				System.out.println("count2: " + count2);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		@Test
		public void test2() {
			Connection connection = null;
			PreparedStatement statement = null;
			try {
				connection = JDBCUtil.getConnection();
				
				connection.setAutoCommit(false);// 将自动提交数据库改为false
				
				String sql1 = "UPDATE account SET money=money-1000 WHERE name='张三'";
				statement = connection.prepareStatement(sql1);
				int count1 = statement.executeUpdate();
				System.out.println("count1: " + count1);
				
				int i = 3 / 0; // ArithmeticException
				
				String sql2 = "UPDATE account SET money=money+1000 WHERE name='李四'";
				statement = connection.prepareStatement(sql2);
				int count2 = statement.executeUpdate();
				System.out.println("count2: " + count2);
				
				// 当减钱和加钱这两个操作都完成了之后，才去手动提交事物
				connection.commit();
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					connection.rollback();// 回滚
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		
		
		// 使用jdbc调用存储过程(了解一下)
		@Test
		public void test55() {
			Connection connection = null;
			CallableStatement callableStatement = null;
			ResultSet resultSet = null;
			try {
				connection = JDBCUtil.getConnection();
				callableStatement = connection.prepareCall("CALL show_goods");
				resultSet = callableStatement.executeQuery();
				while (resultSet.next()) {
					int goodsId = resultSet.getInt("goods_id");
					String goodsName = resultSet.getString("goods_name");
					int goodsNumber = resultSet.getInt("goods_number");
					System.out.println("goodsId:" + goodsId + ", goodsName: " + goodsName +", goodsNumber: " + goodsNumber);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	
}
